﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using Dapper;

namespace Core.DatabaseAccess
{
    public class Base
    {
        public static IEnumerable<T> Query<T>(string sql, Dictionary<string, object> param) where T : class
        {
            using (IDbConnection connection = Connection.OpenConnection())
            {
                return connection.Query<T>(sql, Base.ParseParametersToDynamicParameters(param));
            }
        }

        public static int Save<T>(string sql, Dictionary<string, object> param)
        {
            using (IDbConnection connection = Connection.OpenConnection())
            {
                return connection.Execute(sql, Base.ParseParametersToDynamicParameters(param), commandType: CommandType.Text);
            }
        }

        public static void Save(string sql, Dictionary<string, object> param)
        {
            using (IDbConnection connection = Connection.OpenConnection())
            {
                connection.Execute(sql, Base.ParseParametersToDynamicParameters(param), commandType: CommandType.Text);
            }
        }

        private static DynamicParameters ParseParametersToDynamicParameters(Dictionary<string, object> param)
        {
            DynamicParameters newParam = new DynamicParameters();

            foreach (KeyValuePair<string, object> keyValue in param)
            {
                newParam.Add(keyValue.Key, keyValue.Value);
            }

            return newParam;
        }
    }
}
